package com.lanxiaoye.shoppingSystem.web;


import com.lanxiaoye.shoppingSystem.common.Constants;
import com.lanxiaoye.shoppingSystem.common.result.LoginCheck;
import com.lanxiaoye.shoppingSystem.component.ComparatorRecord;
import com.lanxiaoye.shoppingSystem.entity.Category;
import com.lanxiaoye.shoppingSystem.entity.Goods;
import com.lanxiaoye.shoppingSystem.entity.ScanRecord;
import com.lanxiaoye.shoppingSystem.entity.User;
import com.lanxiaoye.shoppingSystem.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by libing on 2016/12/13.
 */
@Controller
@RequestMapping("/login")
public class HomeLoginController extends BaseController{

    @Autowired
    private HomeIndexService homeIndexService;

    @Autowired
    private HomeLoginService homeLoginService;

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/check")
    @ResponseBody
    public LoginCheck loginCheck(HttpServletRequest request, Model model){
        LoginCheck loginCheck = new LoginCheck();
        int exist = 0;
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(name);
        System.out.println(password);
        //检查用户是否存在
        exist = homeLoginService.checkExist(name);
        if(exist != 1){
            loginCheck.setCheckResult(Constants.USER_NOT_EXIST);
            return loginCheck;
        }
        //检查密码是否正确
        User user = homeLoginService.checkPwd(name,password);
        if (user == null || (!user.getName().equals(name) && !user.getEmail().equals(name) && !user.getPhone().equals(name))){
            loginCheck.setCheckResult(Constants.PASSWORD_WRONG);
            return loginCheck;
        }
        //验证无误
        loginCheck.setCheckResult(Constants.LOGIN_SUCCEED);
        return loginCheck;
    }

    @RequestMapping("/jump")
    public String jumpToLoginPage()throws Exception{
        //跳转到登录页面
        return "home/login";
    }

    @RequestMapping("/login")
    public String login(String name,String item,Model model){
        try {
            name = URLDecoder.decode(name,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        User user = userService.getUserByName(name);
        if(user == null){
            user = userService.getUserByPhone(name);
            if(user == null){
                user = userService.getUserByEmail(name);
            }
        }
        List<Category> categoryList = moduleService.getAllCategory();
        List<Goods> topSalesList = goodsService.getTopSalesEight();
        List<ScanRecord> scanRecordList = moduleService.getRecentScan(user.getUserId());
        //将scanRecordList按浏览次数排序
        ComparatorRecord comparator = new ComparatorRecord();
        Collections.sort(scanRecordList,comparator);

        List<Goods> scanRecordGoodsList = new ArrayList<>();
        for (ScanRecord scanRecord:scanRecordList
             ) {
            Goods goods = goodsService.getByGoodsId(scanRecord.getGoodsId());
            scanRecordGoodsList.add(goods);
        }
        model.addAttribute("User",user);
        model.addAttribute("CategoryList",categoryList);
        model.addAttribute("TopSalesList",topSalesList);
        model.addAttribute("ScanRecordGoodsList",scanRecordGoodsList);
        return "/home/home";
    }

/*    @RequestMapping("/login")
    @ResponseBody
    public LoginResult login(Model model, HttpServletRequest request, HttpSession session, User user){
        LoginResult loginResult = new LoginResult();
        try {
            if (user == null){
                throw new EmptyException("[HomeLoginController][login] login:user empty");
            }
            if (session.getAttribute("user_phone") != null && session.getAttribute("user_phone").equals(user.getUser_phone())) {
                throw new BaseException("[HomeLoginController][login] Login000:user has been logined ");
            }
            if (!CheckUtil.checkMobileFormat(user.getUser_phone())) {
                throw new BaseException("[HomeLoginController][login] Login001:incorrect phone");
            } else if (homeLoginService.checkExist(user) == 0) {
                if (user.getUser_type() == 0) {
                    throw new BaseException("[HomeLoginController][login] Login002:unregistered user");
                } else {
                    throw new BaseException("[HomeLoginController][login] Login002:unregistered business_user");
                }
            } else {
                User select_user = homeLoginService.selectPasswordAndKey(user);
                if (!select_user.getUser_password().equals(EncryptUtil.SHA1(user.getUser_password() + EncryptUtil.SHA1(user.getUser_password())))) {
                    throw new BaseException("[HomeLoginController][login] Login003:incorrect password");
                } else {
                    //登录成功
                    loginResult.setMsg("L004");
                    loginResult.setUser(homeIndexService.getUserInfo(user));
                    int messageNumber = homeIndexService.getMessageNum(user);
                    if (messageNumber == 0) {
                        loginResult.setMessageNum(0);
                    } else {
                        loginResult.setMessageActivity(homeIndexService.getMessageActivity(user));
                        loginResult.setMessageNum(messageNumber);
                    }
                    if (user.getUser_type() == 0) {
                        loginResult.setStatus("User login success");
                    } else {
                        loginResult.setStatus("Business_user login success");
                    }
                    session.setAttribute("user_phone", user.getUser_phone());
                    session.setAttribute("user_type", user.getUser_type());
                }
            }
        }catch (EmptyException e){
            loginResult.setStatus("Login_EmptyException");
            loginResult.setMsg(e.getMessage());
            loggerService.insertLog(e.getMessage());
        } catch (BaseException e) {
            loginResult.setStatus("Login_BaseException");
            loginResult.setMsg(e.getMessage());
            loggerService.insertLog(e.getMessage());
        }
        return loginResult;
    }*/
}
